package com.lagou.client;

import com.lagou.RpcRequest;
import com.lagou.serializer.JsonSerializer;
import com.lagou.serializer.RpcDecoder;
import com.lagou.serializer.RpcEncoder;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * 工具类
 */
public class ClientUtils {

    /**
     * 连接服务端
     */
    public static boolean connect(ClientConnection connections, String path) {

        try {

            if (path == null) {
                throw new RuntimeException("no provider");
            }

            System.out.println("connect url:" + path);
            String[] split = path.split(":");

            connections.setIp(split[0]);
            connections.setPort(Integer.parseInt(split[1]));

            ChannelFuture channelFuture = connections.getBootstrap().connect(connections.getIp(), connections.getPort());
            connections.setChannelFuture(channelFuture);

        } catch (Exception e) {
            e.printStackTrace();
        }

        return true;
    }

    /**
     * 初始化客户端
     */
    public static ClientConnection initClient(String path) {


        UserClientHandler userClientHandler = new UserClientHandler();

        NioEventLoopGroup group = new NioEventLoopGroup();

        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    protected void initChannel(SocketChannel ch) throws Exception {
                        JsonSerializer jsonSerializer = new JsonSerializer();
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast(new RpcEncoder(RpcRequest.class, jsonSerializer));
                        pipeline.addLast(new RpcDecoder(RpcRequest.class, jsonSerializer));
                        pipeline.addLast(userClientHandler);
                    }
                });


        ClientConnection connections = new ClientConnection();
        connections.setBootstrap(bootstrap);
        connections.setGroup(group);
        connections.setUserClientHandler(userClientHandler);

        connect(connections, path);

        return connections;
    }
}
